package com.gentle.config;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author Gentle
 * @date 2019/05/29 : 20:43
 */
@Component
public class ZookeeperConfig {
    @Autowired
    ZookeeperProperties zookeeperProperties;

    /**
     *  配置 Zookeeper 客户端，构建连接
     * @return CuratorFramework 对象
     */
    @Bean
    public CuratorFramework curatorFramework() {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(
                zookeeperProperties.getServer(),
                zookeeperProperties.getSessionTimeoutMs(),
                zookeeperProperties.getConnectionTimeoutMs(),
                new RetryNTimes(zookeeperProperties.getRetryCount(), zookeeperProperties.getElapsedTimeMs()));
        curatorFramework.start();
        return curatorFramework;
    }

    /**
     *
     * @param curatorFramework 分布式锁对象
     * @return
     */
    @Bean
    public InterProcessMutex interProcessMutex(CuratorFramework curatorFramework){
        return new InterProcessMutex(curatorFramework,zookeeperProperties.getLockPath());
    }

}
